package com.mall.pay.services;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderCoreService;
import com.mall.order.dto.PayOrderSuccessRequest;
import com.mall.order.dto.PayOrderSuccessResponse;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.checkerframework.checker.signature.qual.PolySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Autowired
    PaymentMapper paymentMapper;

    @Reference(timeout = 3000,check = false)
    OrderCoreService orderCoreService;

    /*
         获取支付二维码
     */
    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        //  1. 向支付宝后台发请求，获取支付二维码
        String fileName = payHelper.test_trade_precreate(request);

        //  2. 如果获取支付二维码失败，直接返回二维码获取失败
        if (fileName == null) {
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        //  3. 如果获取支付二维码成功
        //     a. tb_payment 插入订单对应的一条支付记录(待支付) PAY_PROCESSING("1","支付处理中")
        //     b. 将获取到的支付二维码返回给前端
        Payment payment = new Payment();
        payment.setStatus("1");
        payment.setOrderId(request.getTradeNo());
        payment.setPayerUid(request.getUserId());
        payment.setPayerAmount(request.getTotalFee());
        payment.setOrderAmount(request.getTotalFee());
        payment.setPayWay(request.getPayChannel());
        payment.setCreateTime(new Date());
        payment.setUpdateTime(new Date());
        paymentMapper.insertSelective(payment);
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(fileName);

        return alipaymentResponse;
    }

    /*
           查询订单的支付结果
     */
    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        AlipayQueryRetResponse response = new AlipayQueryRetResponse();
        //  根据订单id查询订单支付结果
        boolean success = payHelper.test_trade_query(request);
        String orderId = request.getTradeNo();
        PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
        payOrderSuccessRequest.setOrderId(orderId);

        if (success) {
            // 支付成功
            // 1. 修改tb_payment中的对应订单的支付状态，支付成功时间，完成时间 PAY_SUCCESS("2","支付成功")
            //orderCoreService.payOrderSuccess()
            //  通过调用订单服务来完成
            // 2. 修改订单状态 ——> 已支付
            // 3. 访问tb_stock扣减锁定库存
            //     a.  根据订单id，查询到所有订单商品条目
            //     b.  遍历每一个订单商品条目，根据购买的数量，扣减对应商品的锁定库存
            PayOrderSuccessResponse payOrderSuccessResponse = orderCoreService.payOrderSuccess(payOrderSuccessRequest);
            Payment payment = new Payment();
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            payment.setOrderId(orderId);
            payment.setStatus("2");
            payment.setPaySuccessTime(new Date());
            payment.setCompleteTime(new Date());
            int effectRow = paymentMapper.updateByExampleSelective(payment, example);
            if (effectRow < 1) {
                throw new BizException(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode(),PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
            }
            response.setMsg("支付成功");
        } else {
            // 支付失败
            // 1. 修改tb_payment中的对应订单的支付状态，支付成功时间，完成时间  PAY_FAIL("3","支付失败");
            Payment payment = new Payment();
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            payment.setOrderId(orderId);
            payment.setStatus("3");
            payment.setUpdateTime(new Date());
            payment.setCompleteTime(new Date());
            int effectRow = paymentMapper.updateByExampleSelective(payment, example);
            if (effectRow < 1) {
                throw new BizException(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode(),PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
            }
            response.setMsg("订单未支付");
        }

        return response;
    }
}
